<?php 
	class Bitly_Bitly{
		protected $username;
		protected $appkey;
		
		public function __construct(){
			
			$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
 
        	$options = $bootstrap->getOptions();
        	
        	$this->username = $options['bitly']['username'];        	
        	$this->appkey = $options['bitly']['appkey'];
                 			
		}
		
		/* returns the shortened url */
		public function get_bitly_short_url($url,$format='txt') {
			$connectURL = 'http://api.bit.ly/v3/shorten?login='.$this->username.'&apiKey='.$this->appkey.'&uri='.urlencode($url).'&format='.$format;
			return $this->curl_get_result($connectURL);
		}
	
		/* returns expanded url */
		public function get_bitly_long_url($url,$login,$appkey,$format='txt') {
			$connectURL = 'http://api.bit.ly/v3/expand?login='.$this->username.'&apiKey='.$this->appkey.'&shortUrl='.urlencode($url).'&format='.$format;
			return $this->curl_get_result($connectURL);
		}
		
		/* returns a result form url */
		public function curl_get_result($url) {
			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
			$data = curl_exec($ch);
			curl_close($ch);
			return $data;
		}
		
	function makeLinks($str) {
		$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
		$urls = array();
		$urlsToReplace = array();
		if(preg_match_all($reg_exUrl, $str, $urls)) {
			$numOfMatches = count($urls[0]);
			$numOfUrlsToReplace = 0;
			for($i=0; $i<$numOfMatches; $i++) {
				$alreadyAdded = false;
				$numOfUrlsToReplace = count($urlsToReplace);
				for($j=0; $j<$numOfUrlsToReplace; $j++) {
					if($urlsToReplace[$j] == $urls[0][$i]) {
						$alreadyAdded = true;
					}
				}
				if(!$alreadyAdded) {
					array_push($urlsToReplace, $urls[0][$i]);
				}
			}
			$numOfUrlsToReplace = count($urlsToReplace);
			for($i=0; $i<$numOfUrlsToReplace; $i++) {
				$str = str_replace($urlsToReplace[$i], "<a href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
			}
			return $str;
		} else {
			return $str;
		}
	}
		
	}


?>